<template>
  <div class="login-container">
    <!-- 左侧品牌展示区域 -->
    <div class="brand-section">
      <div class="brand-content">
        <!-- 背景装饰 -->
        <div class="background-decoration">
          <div class="floating-shapes">
            <div class="shape shape-1"></div>
            <div class="shape shape-2"></div>
            <div class="shape shape-3"></div>
            <div class="shape shape-4"></div>
            <div class="shape shape-5"></div>
          </div>
        </div>

        <!-- 品牌信息 -->
        <div class="brand-info">
          <div class="logo-section">
            <div class="logo-icon">
              <el-icon size="60"><Lock /></el-icon>
            </div>
            <h1 class="brand-title">美发会员管理系统</h1>
          </div>




        </div>
      </div>
    </div>

    <!-- 右侧登录注册区域 -->
    <div class="auth-section">
      <div class="auth-container">
        <!-- 切换按钮 -->
        <div class="auth-tabs">
          <button
            :class="['tab-btn', { active: activeTab === 'login' }]"
            @click="switchTab('login')"
          >
            登录
          </button>
          <button
            :class="['tab-btn', { active: activeTab === 'register' }]"
            @click="switchTab('register')"
          >
            注册
          </button>
        </div>

        <!-- 表单卡片容器 -->
        <div class="form-container">
          <transition name="slide" mode="out-in">
            <!-- 登录表单 -->
            <div v-if="activeTab === 'login'" key="login" class="form-card">
              <div class="form-header">
                <h2>欢迎回来</h2>
                <p>请登录您的账户</p>
              </div>

              <!-- 登录方式切换 -->
              <div class="login-type-tabs" v-if="emailConfig.loginEnabled || phoneConfig.loginEnabled">
                <button
                  :class="['type-btn', { active: loginType === 'password' }]"
                  @click="loginType = 'password'"
                >
                  密码登录
                </button>
                <button
                  v-if="emailConfig.loginEnabled"
                  :class="['type-btn', { active: loginType === 'email' }]"
                  @click="loginType = 'email'"
                >
                  邮箱登录
                </button>
                <button
                  v-if="phoneConfig.loginEnabled"
                  :class="['type-btn', { active: loginType === 'phone' }]"
                  @click="loginType = 'phone'"
                >
                  手机登录
                </button>
              </div>

              <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" class="auth-form">
                <!-- 用户名密码登录 -->
                <template v-if="loginType === 'password'">
                  <el-form-item prop="username">
                    <el-input
                      v-model="loginForm.username"
                      placeholder="请输入用户名"
                      prefix-icon="User"
                      size="large"
                      class="form-input"
                    />
                  </el-form-item>
                  <el-form-item prop="password">
                    <el-input
                      v-model="loginForm.password"
                      type="password"
                      placeholder="请输入密码"
                      prefix-icon="Lock"
                      size="large"
                      show-password
                      class="form-input"
                      @keyup.enter="handleLogin"
                    />
                  </el-form-item>

                  <!-- 移除页面上的验证码组件，改为在对话框中显示 -->
                </template>

                <!-- 邮箱验证码登录 -->
                <template v-else-if="loginType === 'email'">
                  <el-form-item prop="email">
                    <el-input
                      v-model="loginForm.email"
                      placeholder="请输入邮箱地址"
                      prefix-icon="Message"
                      size="large"
                      class="form-input"
                    />
                  </el-form-item>
                  <el-form-item prop="emailCode">
                    <div class="code-input-group">
                      <el-input
                        v-model="loginForm.emailCode"
                        placeholder="请输入验证码"
                        prefix-icon="Key"
                        size="large"
                        class="form-input code-input"
                        @keyup.enter="handleLogin"
                      />
                      <el-button
                        type="primary"
                        size="large"
                        class="send-code-btn"
                        :loading="sendingLoginCode"
                        :disabled="loginCodeCountdown > 0"
                        @click="sendLoginVerificationCode"
                      >
                        {{ loginCodeCountdown > 0 ? `${loginCodeCountdown}s` : '发送验证码' }}
                      </el-button>
                    </div>
                  </el-form-item>
                </template>

                <!-- 手机号验证码登录 -->
                <template v-else-if="loginType === 'phone'">
                  <el-form-item prop="phone">
                    <el-input
                      v-model="loginForm.phone"
                      placeholder="请输入手机号"
                      prefix-icon="Phone"
                      size="large"
                      class="form-input"
                    />
                  </el-form-item>
                  <el-form-item prop="phoneCode">
                    <div class="code-input-group">
                      <el-input
                        v-model="loginForm.phoneCode"
                        placeholder="请输入验证码"
                        prefix-icon="Key"
                        size="large"
                        class="form-input code-input"
                        @keyup.enter="handleLogin"
                      />
                      <el-button
                        type="primary"
                        size="large"
                        class="send-code-btn"
                        :loading="sendingPhoneLoginCode"
                        :disabled="phoneLoginCodeCountdown > 0"
                        @click="sendPhoneLoginVerificationCode"
                      >
                        {{ phoneLoginCodeCountdown > 0 ? `${phoneLoginCodeCountdown}s` : '发送验证码' }}
                      </el-button>
                    </div>
                  </el-form-item>
                </template>

                <!-- 记住密码选项（仅密码登录时显示） -->
                <el-form-item class="remember-row" v-if="loginType === 'password'">
                  <div class="remember-container">
                    <el-checkbox v-model="rememberPassword" class="remember-checkbox">
                      记住密码
                    </el-checkbox>
                    <el-button type="text" class="forgot-password" @click="handleForgotPassword">
                      忘记密码？
                    </el-button>
                  </div>
                </el-form-item>

                <el-form-item>
                  <el-button
                    type="primary"
                    size="large"
                    class="auth-btn"
                    :loading="loginLoading"
                    @click="handleLogin"
                  >
                    <span v-if="!loginLoading">立即登录</span>
                    <span v-else>登录中...</span>
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 注册表单 -->
            <div v-else key="register" class="form-card">
              <div class="form-header">
                <h2>创建账户</h2>
                <p>请填写注册信息</p>
              </div>

              <!-- 注册方式切换（当同时启用邮箱和手机号注册时显示） -->
              <div class="register-type-tabs" v-if="emailConfig.registerEnabled && phoneConfig.registerEnabled">
                <button
                  :class="['type-btn', { active: registerType === 'password' }]"
                  @click="registerType = 'password'"
                >
                  普通注册
                </button>
                <button
                  :class="['type-btn', { active: registerType === 'email' }]"
                  @click="registerType = 'email'"
                >
                  邮箱注册
                </button>
                <button
                  :class="['type-btn', { active: registerType === 'phone' }]"
                  @click="registerType = 'phone'"
                >
                  手机注册
                </button>
              </div>
              <!-- 当只启用邮箱注册时 -->
              <div class="register-type-tabs" v-else-if="emailConfig.registerEnabled && !phoneConfig.registerEnabled">
                <button
                  :class="['type-btn', { active: registerType === 'password' }]"
                  @click="registerType = 'password'"
                >
                  普通注册
                </button>
                <button
                  :class="['type-btn', { active: registerType === 'email' }]"
                  @click="registerType = 'email'"
                >
                  邮箱注册
                </button>
              </div>
              <!-- 当只启用手机号注册时 -->
              <div class="register-type-tabs" v-else-if="phoneConfig.registerEnabled && !emailConfig.registerEnabled">
                <button
                  :class="['type-btn', { active: registerType === 'password' }]"
                  @click="registerType = 'password'"
                >
                  普通注册
                </button>
                <button
                  :class="['type-btn', { active: registerType === 'phone' }]"
                  @click="registerType = 'phone'"
                >
                  手机注册
                </button>
              </div>

              <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" class="auth-form">
                <!-- 基本信息字段 -->
                <el-form-item prop="username">
                  <el-input
                    v-model="registerForm.username"
                    placeholder="请输入用户名"
                    prefix-icon="User"
                    size="large"
                    class="form-input"
                  />
                </el-form-item>
                <el-form-item prop="password">
                  <el-input
                    v-model="registerForm.password"
                    type="password"
                    placeholder="请输入密码"
                    prefix-icon="Lock"
                    size="large"
                    show-password
                    class="form-input"
                  />
                </el-form-item>
                <el-form-item prop="confirmPassword">
                  <el-input
                    v-model="registerForm.confirmPassword"
                    type="password"
                    placeholder="请确认密码"
                    prefix-icon="Lock"
                    size="large"
                    show-password
                    class="form-input"
                  />
                </el-form-item>
                <el-form-item prop="nickname">
                  <el-input
                    v-model="registerForm.nickname"
                    placeholder="请输入昵称"
                    prefix-icon="Avatar"
                    size="large"
                    class="form-input"
                  />
                </el-form-item>
                <!-- 邮箱注册字段 -->
                <template v-if="registerType === 'email' || (registerType === 'password' && emailConfig.registerEnabled && !phoneConfig.registerEnabled)">
                  <el-form-item prop="email">
                    <div class="code-input-group">
                      <el-input
                        v-model="registerForm.email"
                        placeholder="请输入邮箱"
                        prefix-icon="Message"
                        size="large"
                        class="form-input code-input"
                      />
                      <el-button
                        type="primary"
                        size="large"
                        class="send-code-btn"
                        :loading="sendingRegisterCode"
                        :disabled="registerCodeCountdown > 0"
                        @click="sendRegisterVerificationCode"
                      >
                        {{ registerCodeCountdown > 0 ? `${registerCodeCountdown}s` : '发送验证码' }}
                      </el-button>
                    </div>
                  </el-form-item>

                  <!-- 邮箱验证码输入框 -->
                  <el-form-item prop="emailCode">
                    <el-input
                      v-model="registerForm.emailCode"
                      placeholder="请输入邮箱验证码"
                      prefix-icon="Key"
                      size="large"
                      class="form-input"
                    />
                  </el-form-item>
                </template>

                <!-- 手机号注册字段 -->
                <template v-if="registerType === 'phone' || (registerType === 'password' && phoneConfig.registerEnabled && !emailConfig.registerEnabled)">
                  <el-form-item prop="phone">
                    <div class="code-input-group">
                      <el-input
                        v-model="registerForm.phone"
                        placeholder="请输入手机号"
                        prefix-icon="Phone"
                        size="large"
                        class="form-input code-input"
                      />
                      <el-button
                        type="primary"
                        size="large"
                        class="send-code-btn"
                        :loading="sendingPhoneRegisterCode"
                        :disabled="phoneRegisterCodeCountdown > 0"
                        @click="sendPhoneRegisterVerificationCode"
                      >
                        {{ phoneRegisterCodeCountdown > 0 ? `${phoneRegisterCodeCountdown}s` : '发送验证码' }}
                      </el-button>
                    </div>
                  </el-form-item>

                  <!-- 手机号验证码输入框 -->
                  <el-form-item prop="phoneCode">
                    <el-input
                      v-model="registerForm.phoneCode"
                      placeholder="请输入手机验证码"
                      prefix-icon="Key"
                      size="large"
                      class="form-input"
                    />
                  </el-form-item>
                </template>

                <!-- 普通注册时的邮箱和手机号字段（可选） -->
                <template v-if="registerType === 'password'">
                  <!-- 邮箱字段（可选，不需要验证码） -->
                  <el-form-item prop="email" v-if="!emailConfig.registerEnabled">
                    <el-input
                      v-model="registerForm.email"
                      placeholder="请输入邮箱（可选）"
                      prefix-icon="Message"
                      size="large"
                      class="form-input"
                    />
                  </el-form-item>

                  <!-- 手机号字段（可选，不需要验证码） -->
                  <el-form-item prop="phone" v-if="!phoneConfig.registerEnabled">
                    <el-input
                      v-model="registerForm.phone"
                      placeholder="请输入手机号（可选）"
                      prefix-icon="Phone"
                      size="large"
                      class="form-input"
                    />
                  </el-form-item>
                </template>

                <!-- 移除页面上的验证码组件，改为在对话框中显示 -->

                <el-form-item>
                  <el-button
                    type="primary"
                    size="large"
                    class="auth-btn register-btn"
                    :loading="registerLoading"
                    @click="handleRegister"
                  >
                    <span v-if="!registerLoading">立即注册</span>
                    <span v-else>注册中...</span>
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </transition>
        </div>
      </div>
    </div>

    <!-- 验证码对话框 -->
    <el-dialog
      v-model="captchaDialogVisible"
      title="安全验证"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      center
      class="captcha-dialog"
    >
      <div class="captcha-dialog-content">
        <div class="captcha-header">
          <el-icon class="security-icon"><Lock /></el-icon>
          <h3>请完成安全验证</h3>
          <p>为了保护您的账户安全，请完成以下验证</p>
        </div>

        <div class="captcha-wrapper">
          <CaptchaComponent
            ref="dialogCaptchaRef"
            :type="captchaConfig.type"
            :required="true"
            @verify-success="handleDialogCaptchaSuccess"
            @verify-failed="handleDialogCaptchaFailed"
          />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelCaptchaDialog" :disabled="captchaVerifying">
            取消
          </el-button>
          <el-button
            type="primary"
            @click="confirmCaptchaDialog"
            :loading="captchaVerifying"
            :disabled="!captchaVerified"
          >
            {{ captchaVerifying ? '验证中...' : '确认' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Lock, User, Setting, DataAnalysis } from '@element-plus/icons-vue'
import { login, register } from '../api/auth'
import { useUserStore } from '../stores/user'
import { startTokenRefresh } from '../utils/tokenUtils'
import { saveLoginInfo, getSavedLoginInfo, clearLoginInfo } from '../utils/storage'
import { sendRegisterCode, sendLoginCode, verifyRegisterCode, verifyLoginCode, getEmailConfigStatus } from '../api/emailVerification'
import { sendRegisterCode as sendPhoneRegisterCode, sendLoginCode as sendPhoneLoginCode, verifyRegisterCode as verifyPhoneRegisterCode, verifyLoginCode as verifyPhoneLoginCode } from '../api/phone'
import { getPhoneConfigStatus } from '../api/systemConfig'
import { isCaptchaRequired } from '../api/captcha'
import CaptchaComponent from '../components/CaptchaComponent.vue'

const router = useRouter()
const userStore = useUserStore()
const activeTab = ref('login')
const loginLoading = ref(false)
const registerLoading = ref(false)
const loginFormRef = ref()
const registerFormRef = ref()
const dialogCaptchaRef = ref()
const rememberPassword = ref(false)
const loginType = ref('password') // 'password' 或 'email' 或 'phone'
const registerType = ref('password') // 'password' 或 'email' 或 'phone'

// 验证码对话框相关状态
const captchaDialogVisible = ref(false)
const captchaVerified = ref(false)
const captchaVerifying = ref(false)
const pendingLoginData = ref(null) // 存储待登录的数据
const pendingRegisterData = ref(null) // 存储待注册的数据
const currentAction = ref('') // 'login' 或 'register'

// 邮箱功能配置
const emailConfig = reactive({
  enabled: false,
  registerEnabled: false,
  loginEnabled: false
})

// 手机号功能配置
const phoneConfig = reactive({
  enabled: false,
  registerEnabled: false,
  loginEnabled: false
})

// 验证码配置
const captchaConfig = reactive({
  loginRequired: false,
  registerRequired: false,
  type: 'image'
})

// 验证码相关状态
const sendingRegisterCode = ref(false)
const sendingLoginCode = ref(false)
const sendingPhoneRegisterCode = ref(false)
const sendingPhoneLoginCode = ref(false)
const registerCodeCountdown = ref(0)
const loginCodeCountdown = ref(0)
const phoneRegisterCodeCountdown = ref(0)
const phoneLoginCodeCountdown = ref(0)

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  email: '',
  emailCode: '',
  phone: '',
  phoneCode: ''
})

// 注册表单
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  email: '',
  phone: '',
  emailCode: '',
  phoneCode: ''
})

// 登录表单验证规则
const loginRules = computed(() => {
  if (loginType.value === 'password') {
    return {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ]
    }
  } else if (loginType.value === 'email') {
    return {
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      emailCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { len: 6, message: '验证码长度为6位', trigger: 'blur' }
      ]
    }
  } else if (loginType.value === 'phone') {
    return {
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
      ],
      phoneCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { len: 6, message: '验证码长度为6位', trigger: 'blur' }
      ]
    }
  }
})

// 注册表单验证规则
const registerRules = computed(() => {
  const rules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== registerForm.password) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    nickname: [
      { required: true, message: '请输入昵称', trigger: 'blur' }
    ]
  }

  // 根据注册方式动态添加验证规则
  if (registerType.value === 'email' || (registerType.value === 'password' && emailConfig.registerEnabled && !phoneConfig.registerEnabled)) {
    // 邮箱注册或只启用邮箱注册的普通注册
    rules.email = [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ]
    rules.emailCode = [
      { required: true, message: '请输入邮箱验证码', trigger: 'blur' },
      { len: 6, message: '验证码长度为6位', trigger: 'blur' }
    ]
  } else if (registerType.value === 'phone' || (registerType.value === 'password' && phoneConfig.registerEnabled && !emailConfig.registerEnabled)) {
    // 手机号注册或只启用手机号注册的普通注册
    rules.phone = [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ]
    rules.phoneCode = [
      { required: true, message: '请输入手机验证码', trigger: 'blur' },
      { len: 6, message: '验证码长度为6位', trigger: 'blur' }
    ]
  } else if (registerType.value === 'password') {
    // 普通注册，邮箱和手机号都是可选的
    rules.email = [
      { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ]
    rules.phone = [
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ]
  }

  return rules
})

// 登录处理
const handleLogin = async () => {
  try {
    await loginFormRef.value.validate()

    // 如果是邮箱登录，先验证验证码
    if (loginType.value === 'email') {
      await verifyLoginCode(loginForm.email, loginForm.emailCode)
    } else if (loginType.value === 'phone') {
      await verifyPhoneLoginCode(loginForm.phone, loginForm.phoneCode)
    }

    // 构建登录参数
    let loginParams = {}
    if (loginType.value === 'password') {
      loginParams = {
        username: loginForm.username,
        password: loginForm.password,
        loginType: 'password'
      }

      // 密码登录需要验证图形验证码
      if (captchaConfig.loginRequired) {
        // 显示验证码对话框
        currentAction.value = 'login'
        pendingLoginData.value = loginParams
        showCaptchaDialog()
        return
      }
    } else if (loginType.value === 'email') {
      loginParams = {
        username: loginForm.email,
        code: loginForm.emailCode,
        loginType: 'email'
      }
    } else if (loginType.value === 'phone') {
      loginParams = {
        phone: loginForm.phone,
        code: loginForm.phoneCode,
        loginType: 'phone'
      }
    }

    // 执行登录
    await performLogin(loginParams)
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.response?.data?.message || '登录失败，请重试')
  }
}

// 执行实际的登录请求
const performLogin = async (loginParams) => {
  try {
    loginLoading.value = true
    const response = await login(loginParams)

    // 使用统一的登录方法
    userStore.login(
      response.data.userInfo,
      response.data.token,
      response.data.refreshToken
    )

    // 保存登录信息（如果选择了记住密码且是密码登录）
    if (loginType.value === 'password') {
      saveLoginInfo(loginForm.username, loginForm.password, rememberPassword.value)
    }

    ElMessage.success('登录成功！欢迎回来')
    router.push('/dashboard')
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.response?.data?.message || '登录失败，请重试')
    throw error
  } finally {
    loginLoading.value = false
  }
}

// 注册处理
const handleRegister = async () => {
  try {
    await registerFormRef.value.validate()

    // 根据注册方式验证验证码
    if (registerType.value === 'email' || (registerType.value === 'password' && emailConfig.registerEnabled && !phoneConfig.registerEnabled)) {
      if (registerForm.emailCode) {
        await verifyRegisterCode(registerForm.email, registerForm.emailCode)
      }
    }

    if (registerType.value === 'phone' || (registerType.value === 'password' && phoneConfig.registerEnabled && !emailConfig.registerEnabled)) {
      if (registerForm.phoneCode) {
        await verifyPhoneRegisterCode(registerForm.phone, registerForm.phoneCode)
      }
    }

    // 构建注册参数
    const registerParams = {
      username: registerForm.username,
      password: registerForm.password,
      nickname: registerForm.nickname,
      registerType: registerType.value
    }

    // 根据注册方式添加相应字段
    if (registerType.value === 'email' || (registerType.value === 'password' && emailConfig.registerEnabled && !phoneConfig.registerEnabled)) {
      registerParams.email = registerForm.email
      registerParams.emailCode = registerForm.emailCode
    } else if (registerType.value === 'phone' || (registerType.value === 'password' && phoneConfig.registerEnabled && !emailConfig.registerEnabled)) {
      registerParams.phone = registerForm.phone
      registerParams.phoneCode = registerForm.phoneCode
    } else if (registerType.value === 'password') {
      // 普通注册，可选填邮箱和手机号
      if (registerForm.email) {
        registerParams.email = registerForm.email
      }
      if (registerForm.phone) {
        registerParams.phone = registerForm.phone
      }
    }

    // 验证图形验证码（如果启用）
    if (captchaConfig.registerRequired) {
      // 显示验证码对话框
      currentAction.value = 'register'
      pendingRegisterData.value = registerParams
      showCaptchaDialog()
      return
    }

    // 执行注册
    await performRegister(registerParams)
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error(error.response?.data?.message || '注册失败，请重试')
  }
}

// 执行实际的注册请求
const performRegister = async (registerParams) => {
  try {
    registerLoading.value = true
    await register(registerParams)

    ElMessage.success('注册成功，请登录')
    activeTab.value = 'login'

    // 清空注册表单
    Object.keys(registerForm).forEach(key => {
      registerForm[key] = ''
    })

    // 重置注册方式
    registerType.value = 'password'
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error(error.response?.data?.message || '注册失败，请重试')
    throw error
  } finally {
    registerLoading.value = false
  }
}

// 忘记密码处理
const handleForgotPassword = () => {
  ElMessageBox.alert(
    '请联系系统管理员重置密码，或通过其他方式找回密码。',
    '忘记密码',
    {
      confirmButtonText: '确定',
      type: 'info'
    }
  )
}

// 切换登录/注册标签
const switchTab = (tab) => {
  activeTab.value = tab
}

// 加载邮箱功能配置
const loadEmailConfig = async () => {
  try {
    const response = await getEmailConfigStatus()
    const data = response.data

    // 正确映射后端返回的字段名到前端使用的字段名
    emailConfig.enabled = data.emailEnabled || false
    emailConfig.registerEnabled = data.emailRegisterEnabled || false
    emailConfig.loginEnabled = data.emailLoginEnabled || false

    console.log('邮箱配置加载成功:', emailConfig)
  } catch (error) {
    console.error('加载邮箱配置失败:', error)
    // 如果获取配置失败，使用默认值（禁用所有邮箱功能）
    emailConfig.enabled = false
    emailConfig.registerEnabled = false
    emailConfig.loginEnabled = false

    // 不显示错误消息，避免影响用户体验
    console.warn('使用默认邮箱配置（全部禁用）')
  }
}

// 加载手机号功能配置
const loadPhoneConfig = async () => {
  try {
    const response = await getPhoneConfigStatus()
    const data = response.data

    phoneConfig.enabled = data.phoneEnabled || false
    phoneConfig.registerEnabled = data.phoneRegisterEnabled || false
    phoneConfig.loginEnabled = data.phoneLoginEnabled || false

    console.log('手机号配置加载成功:', phoneConfig)
  } catch (error) {
    console.error('加载手机号配置失败:', error)
    // 如果获取配置失败，使用默认值（禁用所有手机号功能）
    phoneConfig.enabled = false
    phoneConfig.registerEnabled = false
    phoneConfig.loginEnabled = false

    // 不显示错误消息，避免影响用户体验
    console.warn('使用默认手机号配置（全部禁用）')
  }
}

// 加载验证码功能配置
const loadCaptchaConfig = async () => {
  try {
    const loginResponse = await isCaptchaRequired('login')
    const registerResponse = await isCaptchaRequired('register')

    captchaConfig.loginRequired = loginResponse.required || false
    captchaConfig.registerRequired = registerResponse.required || false
    captchaConfig.type = loginResponse.type || 'image'

    console.log('验证码配置加载成功:', captchaConfig)
  } catch (error) {
    console.error('加载验证码配置失败:', error)
    // 如果获取配置失败，使用默认值（禁用验证码功能）
    captchaConfig.loginRequired = false
    captchaConfig.registerRequired = false
    captchaConfig.type = 'image'

    console.warn('使用默认验证码配置（全部禁用）')
  }
}

// 发送注册验证码
const sendRegisterVerificationCode = async () => {
  if (!registerForm.email) {
    ElMessage.error('请先输入邮箱地址')
    return
  }

  try {
    sendingRegisterCode.value = true
    await sendRegisterCode(registerForm.email)
    ElMessage.success('验证码发送成功，请查收邮件')

    // 开始倒计时
    registerCodeCountdown.value = 60
    const timer = setInterval(() => {
      registerCodeCountdown.value--
      if (registerCodeCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.response?.data?.message || '发送验证码失败')
  } finally {
    sendingRegisterCode.value = false
  }
}

// 发送登录验证码
const sendLoginVerificationCode = async () => {
  if (!loginForm.email) {
    ElMessage.error('请先输入邮箱地址')
    return
  }

  try {
    sendingLoginCode.value = true
    await sendLoginCode(loginForm.email)
    ElMessage.success('验证码发送成功，请查收邮件')

    // 开始倒计时
    loginCodeCountdown.value = 60
    const timer = setInterval(() => {
      loginCodeCountdown.value--
      if (loginCodeCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.response?.data?.message || '发送验证码失败')
  } finally {
    sendingLoginCode.value = false
  }
}

// 发送手机号注册验证码
const sendPhoneRegisterVerificationCode = async () => {
  if (!registerForm.phone) {
    ElMessage.error('请先输入手机号')
    return
  }

  try {
    sendingPhoneRegisterCode.value = true
    await sendPhoneRegisterCode(registerForm.phone)
    ElMessage.success('验证码发送成功，请查收短信')

    // 开始倒计时
    phoneRegisterCodeCountdown.value = 60
    const timer = setInterval(() => {
      phoneRegisterCodeCountdown.value--
      if (phoneRegisterCodeCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.response?.data?.message || '发送验证码失败')
  } finally {
    sendingPhoneRegisterCode.value = false
  }
}

// 发送手机号登录验证码
const sendPhoneLoginVerificationCode = async () => {
  if (!loginForm.phone) {
    ElMessage.error('请先输入手机号')
    return
  }

  try {
    sendingPhoneLoginCode.value = true
    await sendPhoneLoginCode(loginForm.phone)
    ElMessage.success('验证码发送成功，请查收短信')

    // 开始倒计时
    phoneLoginCodeCountdown.value = 60
    const timer = setInterval(() => {
      phoneLoginCodeCountdown.value--
      if (phoneLoginCodeCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.response?.data?.message || '发送验证码失败')
  } finally {
    sendingPhoneLoginCode.value = false
  }
}

// 显示验证码对话框
const showCaptchaDialog = () => {
  captchaDialogVisible.value = true
  captchaVerified.value = false
  captchaVerifying.value = false
}

// 验证码对话框相关处理方法
const handleDialogCaptchaSuccess = (data) => {
  console.log('对话框验证码验证成功:', data)
  captchaVerified.value = true
  captchaVerifying.value = false
}

const handleDialogCaptchaFailed = () => {
  console.log('对话框验证码验证失败')
  captchaVerified.value = false
  captchaVerifying.value = false
}

// 取消验证码对话框
const cancelCaptchaDialog = () => {
  captchaDialogVisible.value = false
  captchaVerified.value = false
  captchaVerifying.value = false
  pendingLoginData.value = null
  pendingRegisterData.value = null
  currentAction.value = ''
}

// 确认验证码对话框
const confirmCaptchaDialog = async () => {
  if (!captchaVerified.value) {
    ElMessage.error('请先完成验证码验证')
    return
  }

  try {
    captchaVerifying.value = true

    // 获取验证码数据
    const captchaId = dialogCaptchaRef.value?.getCaptchaId()
    const userInput = dialogCaptchaRef.value?.getUserInput()

    if (!captchaId) {
      ElMessage.error('验证码数据获取失败')
      return
    }

    if (currentAction.value === 'login' && pendingLoginData.value) {
      // 添加验证码信息到登录参数
      const loginParams = {
        ...pendingLoginData.value,
        captchaId: captchaId,
        captchaCode: userInput || captchaId // 滑块验证码使用captchaId
      }

      // 关闭对话框
      captchaDialogVisible.value = false

      // 执行登录
      await performLogin(loginParams)
    } else if (currentAction.value === 'register' && pendingRegisterData.value) {
      // 添加验证码信息到注册参数
      const registerParams = {
        ...pendingRegisterData.value,
        captchaId: captchaId,
        captchaCode: userInput || captchaId // 滑块验证码使用captchaId
      }

      // 关闭对话框
      captchaDialogVisible.value = false

      // 执行注册
      await performRegister(registerParams)
    }

    // 重置状态
    pendingLoginData.value = null
    pendingRegisterData.value = null
    currentAction.value = ''
  } catch (error) {
    console.error('验证码确认失败:', error)
    // 不关闭对话框，让用户重新验证
  } finally {
    captchaVerifying.value = false
  }
}

// 初始化注册方式
const initializeRegisterType = () => {
  // 根据配置自动设置默认注册方式
  if (emailConfig.registerEnabled && phoneConfig.registerEnabled) {
    // 两种都启用，默认普通注册
    registerType.value = 'password'
  } else if (emailConfig.registerEnabled) {
    // 只启用邮箱注册，默认邮箱注册
    registerType.value = 'email'
  } else if (phoneConfig.registerEnabled) {
    // 只启用手机号注册，默认手机号注册
    registerType.value = 'phone'
  } else {
    // 都没启用，默认普通注册
    registerType.value = 'password'
  }
}

// 页面初始化 - 加载保存的登录信息和配置
onMounted(async () => {
  try {
    const savedInfo = getSavedLoginInfo()
    if (savedInfo.remember) {
      loginForm.username = savedInfo.username
      loginForm.password = savedInfo.password
      rememberPassword.value = true
    }

    // 加载功能配置（并行加载，提高性能）
    await Promise.allSettled([
      loadEmailConfig(),
      loadPhoneConfig(),
      loadCaptchaConfig()
    ])

    // 配置加载完成后初始化注册方式
    initializeRegisterType()
  } catch (error) {
    console.error('页面初始化失败:', error)
    // 即使配置加载失败，也不影响基本登录功能
  }
})


</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  background: #f5f7fa;
  overflow: hidden;
}

/* 左侧品牌展示区域 */
.brand-section {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.brand-content {
  position: relative;
  z-index: 2;
  text-align: center;
  padding: 60px;
  max-width: 600px;
}

/* 背景装饰 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.floating-shapes {
  position: relative;
  width: 100%;
  height: 100%;
}

.shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 8s ease-in-out infinite;
}

.shape-1 {
  width: 120px;
  height: 120px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.shape-2 {
  width: 80px;
  height: 80px;
  top: 30%;
  right: 15%;
  animation-delay: 2s;
}

.shape-3 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

.shape-4 {
  width: 60px;
  height: 60px;
  bottom: 40%;
  right: 10%;
  animation-delay: 6s;
}

.shape-5 {
  width: 140px;
  height: 140px;
  top: 60%;
  left: 5%;
  animation-delay: 1s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
    opacity: 0.6;
  }
  50% {
    transform: translateY(-30px) rotate(180deg);
    opacity: 0.9;
  }
}

/* 品牌信息 */
.brand-info {
  width: 100%;
}

.logo-section {
  margin-bottom: 60px;
}

.logo-icon {
  width: 100px;
  height: 100px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 30px;
  backdrop-filter: blur(10px);
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.brand-title {
  font-size: 36px;
  font-weight: 700;
  margin-bottom: 15px;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.brand-subtitle {
  font-size: 18px;
  opacity: 0.9;
  margin: 0;
}

/* 特色功能列表 */
.features-list {
  display: flex;
  flex-direction: column;
  gap: 30px;
  text-align: left;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.feature-item:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateX(10px);
}

.feature-icon {
  font-size: 32px;
  color: rgba(255, 255, 255, 0.9);
}

.feature-text h3 {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.feature-text p {
  font-size: 14px;
  opacity: 0.8;
  margin: 0;
  line-height: 1.5;
}

/* 右侧认证区域 */
.auth-section {
  width: 480px;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  box-shadow: -5px 0 20px rgba(0, 0, 0, 0.1);
}

.auth-container {
  width: 100%;
  max-width: 400px;
}

/* 切换标签 */
.auth-tabs {
  display: flex;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 4px;
  margin-bottom: 40px;
  position: relative;
}

.tab-btn {
  flex: 1;
  padding: 12px 20px;
  border: none;
  background: transparent;
  color: #666;
  font-size: 16px;
  font-weight: 600;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  z-index: 2;
}

.tab-btn.active {
  color: #667eea;
  background: white;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
}

.tab-btn:hover:not(.active) {
  color: #667eea;
  background: rgba(102, 126, 234, 0.05);
}

/* 表单容器 */
.form-container {
  position: relative;
  min-height: 500px;
}

.form-card {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  color: #333;
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.form-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.auth-form {
  margin-top: 20px;
}

/* 登录方式切换标签 */
.login-type-tabs,
.register-type-tabs {
  display: flex;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 3px;
  margin-bottom: 25px;
}

.type-btn {
  flex: 1;
  padding: 8px 16px;
  border: none;
  background: transparent;
  color: #666;
  font-size: 14px;
  font-weight: 500;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.type-btn.active {
  color: #667eea;
  background: white;
  box-shadow: 0 1px 4px rgba(102, 126, 234, 0.15);
}

.type-btn:hover:not(.active) {
  color: #667eea;
  background: rgba(102, 126, 234, 0.05);
}

/* 验证码输入组 */
.code-input-group {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.code-input {
  flex: 1;
}

.send-code-btn {
  width: 120px;
  height: 40px;
  font-size: 14px;
  border-radius: 8px;
  flex-shrink: 0;
}

/* 表单样式 */
.form-input {
  margin-bottom: 16px;
}

.remember-row {
  margin-bottom: 25px !important;
}

.remember-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.remember-checkbox {
  color: #666;
  font-size: 14px;
}

.forgot-password {
  color: #667eea;
  font-size: 14px;
  padding: 0;
  text-decoration: none;
  transition: color 0.3s ease;
}

.forgot-password:hover {
  color: #764ba2;
  text-decoration: underline;
}

.auth-btn {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.auth-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.auth-btn:hover::before {
  left: 100%;
}

.auth-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 35px rgba(102, 126, 234, 0.4);
}

.auth-btn:active {
  transform: translateY(-1px);
}

.register-btn {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
}

/* 卡片切换动画 */
.slide-enter-active,
.slide-leave-active {
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.slide-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.slide-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

/* Element Plus 样式覆盖 */
:deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
  padding: 12px 16px;
  background: #fafbfc;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.15);
  border-color: rgba(102, 126, 234, 0.3);
  background: white;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.25);
  border-color: #667eea;
  background: white;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #667eea;
  border-color: #667eea;
}

:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #667eea;
}

:deep(.el-form-item__label) {
  color: #333;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .brand-content {
    padding: 40px;
  }

  .brand-title {
    font-size: 32px;
  }

  .auth-section {
    width: 420px;
  }
}

@media (max-width: 992px) {
  .login-container {
    flex-direction: column;
  }

  .brand-section {
    min-height: 40vh;
    flex: none;
  }

  .brand-content {
    padding: 30px;
  }

  .brand-title {
    font-size: 28px;
  }

  .features-list {
    flex-direction: row;
    gap: 20px;
    overflow-x: auto;
    padding-bottom: 10px;
  }

  .feature-item {
    min-width: 250px;
    flex-shrink: 0;
  }

  .auth-section {
    width: 100%;
    min-height: 60vh;
    padding: 30px 20px;
  }
}

@media (max-width: 768px) {
  .brand-content {
    padding: 20px;
  }

  .brand-title {
    font-size: 24px;
  }

  .brand-subtitle {
    font-size: 16px;
  }

  .logo-icon {
    width: 80px;
    height: 80px;
  }

  .features-list {
    flex-direction: column;
    gap: 15px;
  }

  .feature-item {
    min-width: auto;
    padding: 15px;
  }

  .auth-container {
    max-width: 100%;
  }

  .form-card {
    padding: 25px 20px;
  }

  .form-header h2 {
    font-size: 24px;
  }
}

@media (max-width: 480px) {
  .brand-section {
    min-height: 35vh;
  }

  .brand-title {
    font-size: 20px;
  }

  .brand-subtitle {
    font-size: 14px;
  }

  .logo-icon {
    width: 60px;
    height: 60px;
  }

  .auth-section {
    padding: 20px 15px;
  }

  .form-card {
    padding: 20px 15px;
  }

  .auth-tabs {
    margin-bottom: 30px;
  }

  .tab-btn {
    padding: 10px 15px;
    font-size: 14px;
  }
}

/* 验证码对话框样式 */
.captcha-dialog {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.captcha-dialog .el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 30px;
  margin: 0;
}

:deep(.captcha-dialog .el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

:deep(.captcha-dialog .el-dialog__body) {
  padding: 30px;
  background: #fafbfc;
}

.captcha-dialog-content {
  text-align: center;
}

.captcha-header {
  margin-bottom: 30px;
}

.security-icon {
  font-size: 48px;
  color: #667eea;
  margin-bottom: 15px;
}

.captcha-header h3 {
  color: #333;
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 10px 0;
}

.captcha-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
  line-height: 1.5;
}

.captcha-wrapper {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 20px 30px;
  background: #fafbfc;
  margin: 0 -30px -30px -30px;
  border-top: 1px solid #e4e7ed;
}

.dialog-footer .el-button {
  min-width: 100px;
  height: 40px;
  border-radius: 8px;
  font-weight: 500;
}

/* 验证码对话框动画 */
:deep(.captcha-dialog .el-dialog) {
  animation: dialogSlideIn 0.3s ease-out;
}

@keyframes dialogSlideIn {
  from {
    opacity: 0;
    transform: translateY(-50px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}
</style>